<template>
  <div class="system-role-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      width="769px"
      @close="closeDialog"
      draggable
      :close-on-click-modal="false"
    >
      <el-form ref="roleFormRef" :model="state.roleInfo" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item :label="$t('message.roleInfo.roleName')">
              <el-input v-model="state.roleInfo.roleName" :placeholder="$t('message.roleInfo.roleName')" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item :label="$t('message.roleInfo.code')">
              <el-input
                v-model="state.roleInfo.code"
                :placeholder="$t('message.roleInfo.code')"
                clearable
                :disabled="state.roleInfo.systemMark === 'SYSTEM'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form-item :label="$t('message.roleInfo.sort')">
              <el-input-number
                v-model="state.roleInfo.sortCode"
                :min="0"
                :max="999"
                controls-position="right"
                placeholder="请输入排序"
                class="w100"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('message.roleInfo.remark')">
              <el-input
                v-model="state.roleInfo.remark"
                type="textarea"
                :placeholder="$t('message.roleInfo.remark')"
                maxlength="150"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl1="24">
            <el-form-item prop="dataScope" :label="$t('message.roleInfo.dataScope')">
              <el-select
                v-model="state.roleInfo.dataScope"
                :placeholder="$t('message.roleInfo.dataScope')"
                style="width: 100%"
                :disabled="state.roleInfo.systemMark === 'SYSTEM'"
              >
                <el-option v-for="d in props.dictData" :key="d.value" :label="d.name" :value="d.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="24"
            :xl1="24"
            v-show="state.roleInfo.dataScope === 'DataScopeDefine' || state.roleInfo.dataScope == 'DataScopeAppointOrgAndChild'"
          >
            <el-form-item prop="DefineScopeOrgList" :label="$t('message.roleInfo.orgList')">
              <el-button @click="openOrgSelector" size="default">{{ t("message.roleInfo.choiceOrg") }}</el-button>
              <el-button @click="openOrgSelector" size="primary" text v-if="state.roleInfo.defineScopeOrgList?.length">
                <el-badge :value="state.roleInfo.defineScopeOrgList?.length" class="item">
                  {{ t("message.roleInfo.choicedOrg") }}
                </el-badge>
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" size="default">{{ t("message.commonBtn.cancel") }}</el-button>
          <el-button type="primary" @click="onSubmit" size="default">{{ t("message.commonBtn.submit") }}</el-button>
        </span>
      </template>
    </el-dialog>
    <OrgSelector ref="orgSelectorRef" @return-data="setChoiceOrgIdList" />
  </div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { reactive, ref } from "vue";
import { SysRole, DictData, SysOrg } from "@/api-services/models/system";
import { feature } from "@/utils/axios-utils";
import roleApi from "@/api-services/apis/system/roleApi";
import OrgSelector from "@/components/Selector/orgSelector.vue";
import { useOrgStore } from "@/stores/modules/org";
import { useI18n } from "vue-i18n";
import { NotificationError, NotificationSuccess } from "@/utils/notification";
const { t } = useI18n();
// 定义子组件向父组件传值/事件
const emits = defineEmits(["refresh", "update:test"]);
const props = defineProps({
  title: String,
  dictData: Array<DictData.SysDictData>
});
const orgSelectorRef = ref<InstanceType<typeof OrgSelector> | null>(null);
const roleFormRef = ref();
const state = reactive({
  orgTree: [] as Array<SysOrg.SysOrg>,
  roleInfo: {} as SysRole.SysRoleInfo,
  dialog: {
    isShowDialog: false,
    type: "",
    title: ""
  }
});

// 打开弹窗
const openDialog = (type: string, roleInfo: SysRole.SysRoleInfo) => {
  state.dialog.type = type;
  if (type === "edit") {
    state.roleInfo = JSON.parse(JSON.stringify(roleInfo));
    state.dialog.title = t("message.roleInfo.editTile");
  } else {
    state.dialog.title = t("message.roleInfo.addTile");
  }
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
  state.roleInfo = {};
};

const openOrgSelector = async () => {
  const orgStore = useOrgStore();
  const orgTree = await orgStore.orgSelectorGet;
  const param = {
    checkStrictly: true,
    defaultValue: state.roleInfo.defineScopeOrgList,
    //requestApi: userCenterApi.orgTree,
    data: orgTree
  };
  orgSelectorRef.value?.orgSelector(param);
};

const setChoiceOrgIdList = (data: number[]) => {
  state.roleInfo.defineScopeOrgList = data;
};
// 提交
const onSubmit = () => {
  roleFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    let err: Error | null;
    if (state.dialog.type === "add") {
      [err] = await feature(roleApi.add(state.roleInfo));
    } else {
      [err] = await feature(roleApi.update(state.roleInfo));
    }
    if (err) {
      NotificationError(err.message);
    } else {
      NotificationSuccess(t("message.commontInfo.success"));
      emits("refresh");
      closeDialog();
    }
  });
};

defineExpose({ openDialog });
</script>

<style scoped lang="scss">
.system-role-dialog-container {
  .menu-data-tree {
    width: 100%;
    padding: 5px;
    border: 1px solid var(--el-border-color);
    border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
  }
}
</style>
